package com.acme.domain.client;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.acme.domain.account.Account;

public class Client implements Serializable {

	private String name;
	private Gender gender;

	private List<Account> accounts = new ArrayList<Account>();

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Client)) return false;

        Client client = (Client) o;

        if (accounts != null ? !accounts.equals(client.accounts) : client.accounts != null) return false;
        if (gender != client.gender) return false;
        if (!name.equals(client.name)) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = name.hashCode();
        result = 31 * result + gender.hashCode();
        result = 31 * result + (accounts != null ? accounts.hashCode() : 0);
        return result;
    }

    public Client(final String name, final Gender gender) {
		this.name = name;

		this.gender = gender;
	}

	public String getName() {
		return name;
	}

	public String getSalutation() {
		if (gender != null) {
			return gender.getSalutation() + " " + name;
		} else {
			return name;
		}
	}

	public Account getAccount(final int id) {
		for (Account acc : accounts) {
			if (acc.getAccountNumber() == id) {
				return acc;
			}
		}
		return null;
	}

	public void addAccount(final Account account) {
		accounts.add(account);
	}

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer();
        sb.append("Client");
        sb.append("{name='").append(name).append('\'');
        sb.append(", gender=").append(gender);
        sb.append(", accounts={");
        for (Account account: accounts){
            sb.append(account.toString()).append(" ");
        }
        sb.append("}}");
        return sb.toString();
    }

	public List<Account> getAccountsList() {
		return Collections.unmodifiableList(accounts);
	}

}
